import { NameSpace } from 'utils/index';
import exceed from 'utils/apimap';
import { Message } from '@teamix/ui';
import { reload } from 'pages/index/actions';
import utils from 'utils';
import intl from '../../../../../../../locale';

const { pathResource } = window.FORCE;

const ns = NameSpace('project-tag');
export const UPDATE_DATA = ns('UPDATE_DATA');
export const LOAD_PAGE = ns('LOAD_PAGE');
export const LOADING_DATA = ns('LOADING_DATA');
export const DELETE_TAG = ns('DELETE_TAG');

export function updateData(data) {
  return (dispatch) => {
    dispatch({
      type: UPDATE_DATA,
      data,
    });
  };
}

export function loadPage(page, search = {}) {
  return (dispatch, getState) => {
    dispatch({
      type: LOADING_DATA,
    });
    let pageSize = 10;
    const { per_page } = search;
    if (per_page) {
      delete search.per_page;
    } else {
      const states = getState().project.projectTags;
      pageSize = states.pageSize;
    }

    exceed
      .fetch({
        api: 'project.tags',
        params: { projectId: pathResource.id },
        data: {
          page,
          per_page: per_page || pageSize,
          search,
          show_signature: true,
        },
      })
      .then((list) => {
        dispatch({
          type: LOAD_PAGE,
          data: Object.assign(list, {
            currentPage: page,
          }),
        });
      })
      .fail(console.log);
  };
}

export function remove(tagName, cbSucc, cbErr) {
  return (dispatch) => {
    exceed
      .fetch({
        api: 'project.tags.delete',
        params: {
          projectId: pathResource.id,
          tagName: utils.revisionEncodeURI(tagName),
        },
      })
      .then((data) => {
        Message.success({
          title: intl.get({
            id: 'code-assets.projectTags.actions.LabelDeleted',
            defaultMessage: '标签已删除',
          }),
        });

        dispatch({
          type: DELETE_TAG,
          data,
        });

        dispatch(reload());

        cbSucc && cbSucc();
      })
      .fail(() => {
        cbErr && cbErr();
      });
  };
}
